package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private static final ExecutorService CACHE_REBUILT_EXECUTOR = Executors.newFixedThreadPool(10);
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        //  布隆过滤解决缓存穿透
        //  Shop shop = queryWithPassThrough(id);
        //  互斥锁解决缓存击穿
        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 布隆过滤解决缓存穿透
     *
     * @param id
     * @return
     */
    private Shop queryWithPassThrough(Long id) {
        Map shopMap = redisTemplate.opsForHash().entries(RedisConstants.CACHE_SHOP_KEY + id);

        if (shopMap.containsKey("NOT_FOUND")) {
            return null;
        }

        if (!shopMap.isEmpty()) {
            return BeanUtil.mapToBean(shopMap, Shop.class, true);
        }

        Shop shop = getById(id);

        if (shop == null) {
            Map map = new HashMap<>();
            map.put("NOT_FOUND", 1);
            redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY + id, map);
            redisTemplate.expire(RedisConstants.CACHE_SHOP_KEY + id, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY + id, BeanUtil.beanToMap(shop));
        redisTemplate.expire(RedisConstants.CACHE_SHOP_KEY + id, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    /**
     * 互斥锁解决缓存击穿
     *
     * @param id
     * @return
     */
    private Shop queryWithMutex(Long id) {
        Map shopMap = redisTemplate.opsForHash().entries(RedisConstants.CACHE_SHOP_KEY + id);

        if (!shopMap.isEmpty() && !shopMap.containsKey("NOT_FOUND")) {
            return BeanUtil.mapToBean(shopMap, Shop.class, true);
        }

        Shop shop = null;
        try {
            boolean lock = tryLock(RedisConstants.LOCK_SHOP_KEY + id);
            if (!lock) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            shop = getById(id);
            if (shop == null) {
                Map map = new HashMap<>();
                map.put("NOT_FOUND", 1);
                redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY + id, map);
            }
            Map map = BeanUtil.beanToMap(shop);
            redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY + id, map);
            redisTemplate.expire(RedisConstants.CACHE_SHOP_KEY + id, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(RedisConstants.LOCK_SHOP_KEY + id);
        }
        return shop;
    }

    /**
     * 逻辑过期解决缓存击穿
     *
     * @param id
     * @return
     */
    private Shop queryWithLogicalExpire(Long id) {
        Map shopMap = redisTemplate.opsForHash().entries(RedisConstants.CACHE_SHOP_KEY + id);

        Object data = shopMap.get("date");
        if (data == null) {
            return null;
        }

        LocalDateTime expireTime = (LocalDateTime) shopMap.get("expireTime");
        if (expireTime.isAfter(LocalDateTime.now())) {
            return (Shop) data;
        }

        if (tryLock(RedisConstants.LOCK_SHOP_KEY)) {
            CACHE_REBUILT_EXECUTOR.submit(() -> {
                try {
                    saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(RedisConstants.LOCK_SHOP_KEY);
                }
            });
        }
        return (Shop) data;
    }

    /**
     * 存入逻辑过期的类
     * @param id
     * @param expiredTime
     */
    private void saveShop2Redis(Long id, Long expiredTime) {
        Shop shop = getById(id);
        Map map = new HashMap<>();
        map.put("date", shop);
        map.put("expiredTime", LocalDateTime.now().plusSeconds(expiredTime));
        redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY + id, map);
    }

    /**
     * 获取互斥锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放互斥锁
     * @param key
     */
    private void unlock(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 更新信息
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result update(Shop shop) {
        updateById(shop);
        if (shop.getId() == null) {
            return Result.fail("id不能为空");
        }
        redisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
